package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Friend;
import com.itheima.domain.mongo.FriendMovement;
import com.itheima.domain.mongo.Movement;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/3/23 20:06
 * @Version 1.0
 */

@Component
public class MovementAsyncService {

    @Autowired
    private MongoTemplate mongoTemplate;

    //线程类的run方法。
    @Async
    public void saveMovementFriend(Movement movement) {

        //2.查询好友列表
        //2-1.构造条件
        Query query = new Query(
                Criteria.where("userId").is(movement.getUserId())
        );
        //2-2.查询列表
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        //3.向好友添加我的动态
        if (CollectionUtil.isNotEmpty(friendList)) {

            //3-1遍历好友列表
            for (Friend friend : friendList) {
                //3-2封装实体
                Long friendId = friend.getFriendId();

                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setUserId(friendId);
                friendMovement.setPublishId(movement.getId());
                friendMovement.setCreated(movement.getCreated());
                //3-3保存动态,注意表名的写法.
                mongoTemplate.save(friendMovement, ConstantUtil.MOVEMENT_FRIEND + friendId);
            }

        }

    }


}
